package com.xd.core.company.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.CompanyInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.xd.common.constant.SysConstant;
import com.xd.common.properties.SendALProperties;
import com.xd.common.util.OCRUtil;
import com.xd.common.util.SecurityUtil;
import com.xd.core.api.service.IRepaymentOrderInfoService;
import com.xd.core.business.dto.IncomingInfoEnableDto;
import com.xd.core.business.entity.InsuranceCompanyInfo;
import com.xd.core.business.entity.ProductCompanyTiered;
import com.xd.core.business.mapper.InsuranceCompanyInfoMapper;
import com.xd.core.business.mapper.ProductCompanyTieredMapper;
import com.xd.core.business.service.IIncomingInfoService;
import com.xd.core.business.service.IMortgageService;
import com.xd.core.business.service.IOutInfoService;
import com.xd.core.business.service.IRepaymentScheduleService;
import com.xd.core.company.dto.*;
import com.xd.core.company.entity.AgencyCompanyCheck;
import com.xd.core.company.entity.BindBank;
import com.xd.core.company.entity.Company;
import com.xd.core.company.entity.CompanyContract;
import com.xd.core.company.mapper.AgencyCompanyCheckMapper;
import com.xd.core.company.mapper.CompanyAccountMapper;
import com.xd.core.company.mapper.CompanyMapper;
import com.xd.core.company.service.IBindBankService;
import com.xd.core.company.service.ICompanyContractService;
import com.xd.core.company.service.ICompanyService;
import com.xd.core.company.vo.*;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.system.entity.SysUser;
import com.xd.core.system.service.ISysUserService;
import com.xd.core.system.vo.SysUserDown;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 公司信息表 前端控制器
 * </p>
 *
 * @author ZX
 * @since 2024-07-24
 */
@Api(tags = "新增企业")
@RestController
@RequestMapping("/system/company")
public class CompanyController {
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IIncomingInfoService iIncomingInfoService;
    @Autowired
    private IMortgageService iMortgageService;
    @Autowired
    private IOutInfoService iOutInfoService;
    @Autowired
    private IRepaymentOrderInfoService iRepaymentOrderInfoService;
    @Autowired
    private IRepaymentScheduleService iRepaymentScheduleService;
    @Autowired
    private CompanyAccountMapper companyAccountMapper;
    @Autowired
    private ICompanyContractService iCompanyContractService;
    @Autowired
    private IBindBankService iBindBankService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private SendALProperties sendALProperties;
    @Autowired
    private AgencyCompanyCheckMapper agencyCompanyCheckMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Autowired
    private ProductCompanyTieredMapper productCompanyTieredMapper;
    @Autowired
    private InsuranceCompanyInfoMapper insuranceCompanyInfoMapper;

    @ApiOperation(value = "身份证识别")
    @PostMapping("identityCardByUrl")
    public JSONObject identityCardByUrl(MultipartFile file) throws Exception {
        return OCRUtil.ORCIdentityCardByFile(file.getInputStream(), sendALProperties.getAccessKeyId(), sendALProperties.getSecret());
    }

    @ApiOperation(value = "营业执照识别")
    @PostMapping("businessLicenseByUrl")
    public JSONObject businessLicenseByUrl(MultipartFile file) throws Exception {
        return OCRUtil.ORCIBusinessLicenseByUFile(file.getInputStream(), sendALProperties.getAccessKeyId(), sendALProperties.getSecret());
    }

    @ApiOperation("平台———停单/启用订单")
    @PostMapping("/enableOrder")
    public void updateOrderIsEnable(@RequestBody IncomingInfoEnableDto incomingInfoEnableDto) {
        iIncomingInfoService.updateStatus(incomingInfoEnableDto);
    }


    @PreAuthorize("hasAnyAuthority('sys:NewInvestors')")
    @ApiOperation("平台———新增资方")
    @PostMapping("/addCapitalUser")
    public void addCapitalUser(@RequestBody AddCapitalUserDto addCapitalUserDto) throws Exception {
        companyService.addCapitalUser(addCapitalUserDto);
    }

    @PreAuthorize("hasAnyAuthority('sys:EditInvestors')")
    @ApiOperation("平台———修改资方")
    @PostMapping("/updateCapitalUser")
    public void updateCapitalUser(@RequestBody AddCapitalUserDto addCapitalUserDto) {
        companyService.updateCapitalUser(addCapitalUserDto);
    }

    @PreAuthorize("hasAnyAuthority('sys:NewAgency')")
    @ApiOperation("资方———新增代理(未审核)")
    @PostMapping("/addAgencyUser")
    public void addAgencyUser(@RequestBody AddAgencyUserDto addAgencyUserDto) {
        companyService.addAgencyUser(addAgencyUserDto);
    }

    @PreAuthorize("hasAnyAuthority('sys:AgentManagement-GoReview')")
    @ApiOperation("平台———审核代理企业")
    @PostMapping("/checkAgencyUser")
    public void checkAgencyUser(@RequestBody CheckAgencyUserDto checkAgencyUserDto) {
        companyService.checkAgencyUser(checkAgencyUserDto);
    }

    @ApiOperation("资方———审核代理企业查看详情")
    @GetMapping("/getCheckDetail")
    public GetCheckDetail getCheckDetail(Integer id) {
        return companyService.getCheckDetail(id);
    }

    @PreAuthorize("hasAnyAuthority('sys:EditAgency','sys:AgentManagement-AgainChange','sys:AgentManagement-Edit')")
    @ApiOperation("资方———重新编辑代理企业")
    @PostMapping("/againAddAgencyUser")
    public void againAddAgencyUser(@RequestBody AddAgencyUserDto addAgencyUserDto) {
        companyService.againAddAgencyUser(addAgencyUserDto);
    }

    @PreAuthorize("hasAnyAuthority('sys:AgentManagement-passViewDetails','sys:AgentManagement')")
    @ApiOperation("通过审核的代理列表")
    @PostMapping("/getAgencyList")
    public Page<CompanyPageVo> getAgencyList(@RequestBody CompanyQuery companyQuery) {
        return companyService.getAgencyList1(companyQuery);
    }


    @ApiOperation("通过审核代理列表--导出")
    @PostMapping("/exportAgencyList")
    public void exportAgencyList(@RequestBody CompanyQuery companyQuery) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);

        companyService.exportAgencyList(companyQuery, missionCenterInfo.getId());
    }
    @PreAuthorize("hasAnyAuthority('sys:AgentManagement-unpassViewDetails')")
    @ApiOperation("未通过审核的代理列表")
    @PostMapping("/getUnCheckAgencyList")
    public Page<CompanyPageVo> getUnCheckAgencyList(@RequestBody CompanyQuery companyQuery) {
        return companyService.getAgencyList(companyQuery);
    }

    @ApiOperation("未通过审核的代理列表--导出")
    @PostMapping("/exportUnCheckAgencyList")
    public void exportUnCheckAgencyList(@RequestBody CompanyQuery companyQuery) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);

        companyService.exportUnCheckAgencyList(companyQuery, missionCenterInfo.getId());
    }

    @ApiOperation("未通过审核--代理详情")
    @GetMapping("/getAgencyList/{id}")
    public CompanyAgencyVo getAgencyDetail(@PathVariable Integer id) {
        return companyService.getAgencyDetail(id);
    }


    @ApiOperation("已通过审核--代理详情")
    @GetMapping("/getPassAgencyList/{companyId}")
    public CompanyAgencyVo getPassAgencyList(@PathVariable Integer companyId) {
        return companyService.getPassAgencyList(companyId);
    }
    @PreAuthorize("hasAnyAuthority('sys:AssetManagement-viewDetails')")
    @ApiOperation("平台--资方列表")
    @PostMapping("/getCapitalList")
    public Page<CapitalPageVo> getCapitalList(@RequestBody CompanyQuery companyQuery) {
        return companyService.getCapitalList(companyQuery);
    }

    @ApiOperation("冻结资方账户")
    @PostMapping("/freezeAccount")
    public void freezeAccount(@RequestBody FreezeAccountDto freezeAccountDto) {
         companyService.freezeAccount(freezeAccountDto);
    }


    @ApiOperation("平台--资方列表--导出")
    @PostMapping("/exportCapitalList")
    public void exportCapitalList(@RequestBody CompanyQuery companyQuery) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);

        companyService.exportCapitalList(companyQuery, missionCenterInfo.getId());
    }


    @ApiOperation("平台--查看资方详情")
    @GetMapping("/getCapitalDetail/{id}")
    public CompanyCapitalVo getCapitalDetail(@PathVariable Integer id) {
        return companyService.getCapitalDetail(id);
    }

    @ApiOperation("平台--编辑资方通道")
    @PostMapping("/updateThoroughFare")
    public void updateThoroughFare(@RequestBody CompanyThoroughFare  companyThoroughFare) {
         companyMapper.updateThoroughFare(companyThoroughFare);
    }

    @ApiOperation("平台--编辑回显--资方详情")
    @GetMapping("/getCapital/{id}")
    public CompanyCapital getCapital(@PathVariable Integer id) {
        return companyService.getCapitalDetails(id);
    }

    @ApiOperation("平台--编辑回显--代理详情")
    @GetMapping("/getAgency/{id}")
    public AgencyCompanyCheck getAgency(@PathVariable Integer id) {
        return agencyCompanyCheckMapper.selectAgencyDetail(id);
    }

    @ApiOperation("平台--资方详情--代理信息")
    @GetMapping("/getCapitalAgencyList/{id}")
    public List<AgencyListVo> getCapitalAgencyList(@PathVariable Integer id) {
        return companyService.getCapitalAgencyList(id);
    }

    @ApiOperation("平台--资方详情--账户信息")
    @GetMapping("/getAccounts/{id}")
    public CompanyAccountDetail getAccounts(@PathVariable Integer id) {
        return companyAccountMapper.selectAccount(id);
    }

    @ApiOperation("资方白名单列表")
    @GetMapping("/getWhileAccountList/{id}")
    public List<BindBank> getAccountList(@PathVariable Integer id) {
        return iBindBankService.getAccountList(id);
    }

    @ApiOperation("收款账户下拉框")
    @GetMapping("/getWhileAccountDown/{id}")
    public List<BindBankVo> getWhileAccountDown(@PathVariable Integer id) {
        return iBindBankService.getWhileAccountDown(id);
    }

    @ApiOperation("平台--资方详情--配置费率")
    @GetMapping("/getConfigureRates/{id}")
    public ConfigureRatesVo getConfigureRates(@PathVariable Integer id) {
        return companyService.getConfigureRates(id);
    }


    @ApiOperation("平台--资方详情--合同管理")
    @GetMapping("/getCompanyContract/{id}")
    public List<CompanyContract> getCompanyContract(@PathVariable Integer id) {
        return iCompanyContractService.getCompanyContract(id);
    }

    @ApiOperation("个人中心--公司资料详情")
    @GetMapping("/getCompanyDetail/{id}")
    public CompanyVo getPersonCenterCapitalDetail(@PathVariable Integer id) {
        return companyService.getCompanyDetail(id);
    }

    @ApiOperation("个人中心--资方详情--代理信息")
    @GetMapping("/getPersonCenterCapitalList/{id}")
    public List<AgencyListVo> getPersonCenterCapitalAgencyList(@PathVariable Integer id) {
        return companyService.getCapitalAgencyList(id);
    }

    @ApiOperation("个人中心--资方详情--配置费率")
    @GetMapping("/getPersonCenterConfigureRates/{id}")
    public ConfigureRatesVo getPersonCenterConfigureRates(@PathVariable Integer id) {
        return companyService.getConfigureRates(id);
    }

    @ApiOperation("首页--代理公司预览")
    @GetMapping("/agencyPreview")
    public AgencyPreview getAgencyPreview() {
        return companyService.getAgencyPreview();
    }

    @ApiOperation("首页--进件预览")
    @PostMapping("/incomingPreview")
    public IncomingPreview getIncomingPreview(@RequestBody HomeQueryDto query) {
        return iIncomingInfoService.getIncomingPreview(query);
    }

    @ApiOperation("首页--公证及抵押办理")
    @PostMapping("/getCertificationAndMortgage")
    public CertificationAndMortgage getCertificationAndMortgage(@RequestBody HomeQueryDto query) {
        return iMortgageService.getCertificationAndMortgage(query);
    }

    @ApiOperation("首页--放款概况")
    @PostMapping("/getOutCounts")
    public OutCounts getOutCounts(@RequestBody HomeQueryDto query) {
        return iOutInfoService.getOutCounts(query);
    }

    @ApiOperation("首页--回款概况")
    @PostMapping("/getReceiveCounts")
    public ReceiveCounts getReceiveCounts(@RequestBody HomeQueryDto query) {
        return iRepaymentOrderInfoService.getReceiveCounts(query);
    }

    @ApiOperation("首页--逾期概览")
    @PostMapping("/getDelayCounts")
    public DelayCounts getDelayCounts(@RequestBody HomeQueryDto query) {
        return iRepaymentScheduleService.getDelayCounts(query);
    }

    @ApiOperation("资方下拉框")
    @GetMapping("/getCapitals")
    public List<CompanyInfoVo> getCapitals() {
        return companyService.getCapitals();
    }

    @ApiOperation("资方下拉框---财务管理")
    @GetMapping("/getCapitals/finance")
    public List<CompanyVo1> getCapitalsFinance() {
        return companyService.getCapitalsFinance();
    }

    @ApiOperation("资方代理下拉框")
    @GetMapping("/getAllCompany")
    public List<CompanyInfoVo> getAllCompany() {
        return companyService.getAllCompany();
    }

    @ApiOperation("资方--代理下拉框")
    @GetMapping("/getAgents/{companyId}")
    public List<CompanyInfoVo> getAgents(@PathVariable Integer companyId) {
        return companyService.getAgents(companyId);
    }


    @ApiOperation("修改进件状态")
    @PutMapping("/updateIncomingStatus")
    public void updateIncomingStatus(@RequestBody UpdateIncomingStatus updateIncomingStatus) {
        companyService.updateIncomingStatus(updateIncomingStatus);
    }

    @ApiOperation("修改代扣开关状态")
    @PutMapping("/updateWithholdSwitchStatus")
    public void updateWithholdSwitchStatus(@RequestBody UpdateWithholdSwitchStatus updateWithholdSwitchStatus) {
        companyService.updateWithholdSwitchStatus(updateWithholdSwitchStatus);
    }


    @ApiOperation("资方商务经理下拉框")
    @GetMapping("/getCapitalBusinessManager")
    public ManagerVos getCapitalBusinessManager() {
        String userType = SecurityUtil.getLoginUser().getUser().getUserType();
        ManagerVos managerVos = new ManagerVos();
        managerVos.setIsSuper(userType);
        List<SysUser> list = iSysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getCompanyType, SysConstant.USER_COMPANY_TYPE_ONE)
                .eq(SysUser::getStatus, SysConstant.USER_ENABLE));
        managerVos.setUsers(BeanUtil.copyToList(list, SysUserDown.class));
        managerVos.setSysUser(SecurityUtil.getLoginUser().getUser());
        return managerVos;
    }

    @ApiOperation("代理商务经理下拉框")
    @GetMapping("/getBusinessManager/{companyId}")
    public SysUserDown getBusinessManager(@PathVariable Integer companyId) {
        Integer businessManager = companyService.getById(companyId).getBusinessManager();
        return BeanUtil.copyProperties(iSysUserService.getById(businessManager), SysUserDown.class);
    }

    @ApiOperation("资方详情公共")
    @GetMapping("/getCapitalDetailPublic/{companyId}")
    public CompanyDetailVo getCapitalDetailPublic(@PathVariable Integer companyId) {
        return companyService.getCapitalDetailPublic(companyId);
    }

    @ApiOperation("开户认证--编辑返显")
    @GetMapping("/getAccountOpeningAuthentication/{companyId}")
    public ElectronicAccountsVo getAccountOpeningAuthentication(@PathVariable Integer companyId) {
        return companyMapper.getAccountOpeningAuthentication(companyId);
    }


    @ApiOperation("进件机构下拉框")
    @GetMapping("/getIncomingCompanyLists")
    public List<CompanyInfoVo> getIncomingCompanyLists() {
        List<CompanyInfoVo> list = CollectionUtil.newArrayList();
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer loginCompanyId = SecurityUtil.getLoginCompanyId();
        if (companyType.equals(SysConstant.USER_COMPANY_TYPE_FOUR)){
            //集团
            list = companyMapper.getBlocCapital(loginCompanyId);
            List<Integer> capitalCompanyIds = list.stream().map(CompanyInfoVo::getCompanyId).collect(Collectors.toList());
            List<CompanyInfoVo> blocAgents =companyMapper.getCapiptalAgents(capitalCompanyIds);
            list.addAll(blocAgents);
        }else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE)){
            //平台
            list = companyMapper.getAllCompany();
        }else {
            //资方
            list = companyMapper.getAgents(loginCompanyId);
        }
        CompanyInfoVo companyInfoVo = new CompanyInfoVo();
        companyInfoVo.setCompanyId(0);
        companyInfoVo.setCompanyName("平台");
        list.add(0, companyInfoVo);
        return list;
    }

    @ApiOperation("阶梯放款比例收费")
    @GetMapping("/getProductCompanyTiered/{companyId}")
    public List<ProductCompanyTiered> getProductCompanyTiered(@PathVariable Integer companyId) {
        return productCompanyTieredMapper.selectList(new LambdaQueryWrapper<ProductCompanyTiered>().eq(ProductCompanyTiered::getCompanyId, companyId));
    }
    @PreAuthorize("hasAnyAuthority('sys:NewGroupInvestors')")
    @ApiOperation("新建集团")
    @PostMapping("/addBloc")
    public void addBloc(@RequestBody AddCapitalUserDto addCapitalUserDto) {
        companyService.addBloc(addCapitalUserDto);
    }

    @ApiOperation("修改集团")
    @PostMapping("/updateBloc")
    public void updateBloc(@RequestBody AddCapitalUserDto addCapitalUserDto) {
        companyService.updateBloc(addCapitalUserDto);
    }


    @PreAuthorize("hasAnyAuthority('sys:GroupCompanyRecharge-viewDetails')")
    @ApiOperation("集团列表")
    @PostMapping("/getBlocList")
    public Page<BlocPageVo> getBlocList(@RequestBody BlocQuery blocQuery){
        return companyService.getBlocList(blocQuery);
    }

    @PreAuthorize("hasAnyAuthority('sys:EditGroupInvestors')")
    @ApiOperation("平台--编辑回显--集团详情")
    @GetMapping("/getBloc/{id}")
    public CompanyBloc getBloc(@PathVariable Integer id) {
        return companyService.getBloc(id);
    }


    @ApiOperation("平台--集团详情")
    @GetMapping("/getBlocDetail/{id}")
    public CompanyBloc getBlocDetail(@PathVariable Integer id) {
        return companyService.getBloc(id);
    }

    @ApiOperation("平台--集团详情--子公司信息")
    @GetMapping("/getBlocCapitals/{id}")
    public List<CompanyCapitals> getBlocCapitals(@PathVariable Integer id) {
        return companyService.getBlocCapitals(id);
    }

    @ApiOperation("集团下拉框")
    @GetMapping("/getBlocs")
    public List<CompanyBlocVo> getBlocs(){
        List<Company> list = companyService.list(new LambdaQueryWrapper<Company>().eq(Company::getCompanyType, SysConstant.COMPANY_TYPE_THREE));
        return BeanUtil.copyToList(list,CompanyBlocVo.class);
    }

    @ApiOperation("保单贷-资方下拉框")
    @GetMapping("/getInsuranceDrop")
    public List<CompanyInfoVo> getInsuranceDrop(){
      return companyService.getInsuranceCompanys();
    }

    @ApiOperation("资方--投保公司下拉框")
    @GetMapping("/getInsuranceCompanyS/{companyId}")
    public List<InsuranceCompanyInfoVo> getInsuranceCompanyS(@PathVariable Integer companyId){
        List<InsuranceCompanyInfo> list = insuranceCompanyInfoMapper.
                selectList(new LambdaQueryWrapper<InsuranceCompanyInfo>()
                        .eq(InsuranceCompanyInfo::getCompanyId, companyId)
                        .eq(InsuranceCompanyInfo::getIsEnable,1));
        return BeanUtil.copyToList(list,InsuranceCompanyInfoVo.class);
    }

    @ApiOperation("支付通道下拉框")
    @GetMapping("/getPayPassList/{companyId}")
    public String getPayPassList(@PathVariable Integer companyId){
        return companyMapper.getPayPassList(companyId);
    }

    @ApiOperation("修改备注")
    @PostMapping("/updateRemark")
    public void updateRemark(@RequestBody CompanyRemark companyRemark){
        companyMapper.updateRemark(companyRemark);
    }
    @ApiOperation("开放三方接口开关")
    @PostMapping("/updateOpenStatus")
    public void updateOpenStatus(@RequestBody UpdateOpenStatus updateOpenStatus){
        companyMapper.updateOpenStatus(updateOpenStatus);
    }
}
